import json
import os
from socket import *

import openpyxl
import xlrd
import xlwt
import datetime

from openpyxl import load_workbook
from xlrd import open_workbook
from xlutils.copy import copy
import time


# date_day = str(datetime.datetime.now().year) + "-" + str(datetime.datetime.now().month) + "-" + str(
#     datetime.datetime.now().day)
# savepath = os.path.abspath(os.path.dirname(os.getcwd())) + "/" + date_day + '.xls'
# book = xlwt.Workbook(encoding='utf-8', style_compression=0)
# sheet = book.add_sheet('打卡', cell_overwrite_ok=False)
# col = ('S', 'I', '签到时间', '签退时间', 'ER', 'R','DATE')
# line_i=0
# same=0
# addr_assist=''
# for i in range(0, 7):
#     sheet.write(0, i, col[i])
# book.save(savepath)


def send_msg(udp_socket):
    dest_ip = input("请输入目标IP：")
    dest_port = int(input("请输入端口号："))
    data = input("请输入要发送的内容：")
    udp_socket.sendto(data.encode('GBK'), (dest_ip, dest_port))


def recv_msg(udp_socket):
    while True:
        recv_data = udp_socket.recvfrom(1024)
        original_data = recv_data[0].decode('GBK')
        print(recv_data)

        count_n = 0
        record_line = 1;
        global same, data_dict
        global line_i
        global addr_assist
        date_day = str(datetime.datetime.now().year) + "-" + str(datetime.datetime.now().month) + "-" + str(
            datetime.datetime.now().day)
        savepath = os.path.abspath(os.path.dirname(os.getcwd())) + "/" + date_day + '.xlsx'

        data_dict = json.loads(original_data)

        if (os.path.exists(savepath)):
            wb = openpyxl.load_workbook(savepath)
            wa = wb.active

        else:
            print("none")
            wb = openpyxl.Workbook()  # 创建一个excel文件
            wa = wb.active  # 获得一个的工作表
            wa.title = "打卡"
            wa.append(['S', 'ID', '签到', '签退', 'ER', 'R', 'DATE'])

        current_time = str(datetime.datetime.now())[-15:-7]

        for i in range(1, wa.max_row + 1)[::-1]:
            if (wb["打卡"].cell(row=i, column=2).value) == data_dict['I']:
                record_line = i
                break

        if wb["打卡"].cell(row=record_line, column=1).value == "ok":
            sendback = "ok"
            print("签到1")
            wa.append(
                ["no", data_dict['I'], current_time, data_dict['W'], data_dict['ER'], data_dict['R'],
                 current_time])
        elif wb["打卡"].cell(row=record_line, column=1).value == "no":
            print("签退1")
            sendback = "end"
            wb["打卡"].cell(row=record_line, column=4, value=current_time)
            wb["打卡"].cell(row=record_line, column=1, value="ok")
        else:
            print("签到2")
            sendback = "ok"
            wa.append(
                ["no", data_dict['I'], current_time, data_dict['W'], data_dict['ER'], data_dict['R'],
                 current_time])
        print("num : ", count_n)

        wb.save(savepath)

        # if(line_i==0):
        #     sheet.write(line_i + 1, 6, "0")
        #     book.save(savepath)
        # excel_file = xlrd.open_workbook(savepath)
        # wb = open_workbook(savepath)
        # read_sheet = wb.sheet_by_index(0)

        # line_i=len(open(savepath,encoding='gbk', errors="ignore").readlines())
        # if(read_sheet.cell(100,6).value!='NULL'):
        # print("read : ", read_sheet.cell(1, 6).value)
        # while True:
        #     if str(read_sheet.cell_value(line_i,6))!='a':
        #         line_i=1+line_i
        #     else :
        #         break
        #
        # print("line : ",line_i)
        # print("read : ",read_sheet.cell(line_i,6).value)

        print("date : ", current_time)
        # print("s: ",data_dict['S'])
        print("收到内容：", original_data)
        # print("发送地址：{}:{}".format(recv_data[1][0], recv_data[1][1]))
        print("发送内容：", sendback.encode('GBK'))
        udp_socket.sendto(sendback.encode('GBK'), (recv_data[1][0], 8266))
        # udp_socket.sendto(data.encode('GBK'), (dest_ip, dest_port))


def main():
    udp_socket = socket(AF_INET, SOCK_DGRAM)
    local_addr = ('', 45555)
    udp_socket.bind(local_addr)
    while True:
        print("*" * 30)
        print("1.发送信息")
        print("2.接收信息")
        print("*" * 30)
        num = input("请输入选项(回车结束)：")
        if not num:
            print("Bye")
            break
        elif num == "1":
            send_msg(udp_socket)
        elif num == "2":
            # while True:
            #     recv_data = udp_socket.recvfrom(1024)
            #     original_data = recv_data[0].decode('GBK')
            #     print(original_data)
            recv_msg(udp_socket)
        else:
            print("无效输入！")
            continue


if __name__ == '__main__':
    main()
